import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import dts from 'vite-plugin-dts'
import { fileURLToPath, URL } from 'node:url'
import { readdirSync } from 'node:fs'
import { filter, map } from 'lodash-es'

// const COMP_NAMES = ['Alert', 'Button', 'Collapse', 'Dropdown', 'Icon', 'Message', 'Tooltip']

function getDirectoriesSync(basePath: string) {
  const entries = readdirSync(basePath, { withFileTypes: true })
  return map(
    filter(entries, entry => entry.isDirectory()),
    entry => entry.name
  )
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    dts({
      tsconfigPath: './tsconfig.build.json',
      outDir: 'dist/types'
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  build: {
    outDir: resolve(__dirname, 'dist/es'),
    sourcemap: true,
    lib: {
      entry: resolve(__dirname, './src/index.ts'),
      name: 'My-Element',
      fileName: 'index',
      formats: ['es']
    },
    rollupOptions: {
      external: [
        'vue',
        '@fortawesome/fontawesome-svg-core',
        '@fortawesome/free-solid-svg-icons',
        '@fortawesome/vue-fontawesome'
      ],
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor'
          }
          if (id.includes('src/hooks')) {
            return 'hooks'
          }
          if (id.includes('src/utils')) {
            return 'utils'
          }
          // for (const item of COMP_NAMES) {
          for (const item of getDirectoriesSync('./src/components')) {
            if (id.includes(`src/components/${item}`)) {
              return item
            }
          }
        }
      }
    }
  }
})
